package proxy.jdk2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ValidatorHandler implements InvocationHandler {

    private Object target;

    public ValidatorHandler(Object target){
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        for (Object arg : args) {
            this.validate((Integer) arg);
        }
        return method.invoke(target, args);
    }


    public static Object getProxy(Object target){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                new ValidatorHandler(target));
    }


    private void validate(Integer arg){
        System.out.println("开始校验参数："+arg);
        if ((arg<0)) {
            throw new IllegalArgumentException("非法参数异常："+ arg);
        }
    }


}
